package com.teamsun.service;

import com.alibaba.fastjson.JSONObject;
import com.teamsun.cache.CacheManager;
import com.teamsun.entity.HttpResult;
import com.teamsun.entity.IRequestInfo;
import com.teamsun.entity.SelfDefine;
import com.teamsun.rptcfg.BaseRpt;
import com.teamsun.rptcfg.BaseRptColumn;
import com.teamsun.util.Constants;
import com.teamsun.util.RequestParamToMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义报表
 */
@Service("selfDefineRpt")
public class SelfDefineRpt  implements ICallThirdService {

    @Autowired
    private HttpClientService httpClientService;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 封装参数
     * @param request
     * @param sysCode  接入系统编码
     * @return
     */
    @Override
    public IRequestInfo wrapRequestInfo(HttpServletRequest request, String sysCode) {
        String rptId = request.getParameter("rptId");  // 报表ID
        String rptURL = request.getParameter("rptURL");  // 报表访问路径
        String rptIdx = request.getParameter("rptIdx");  // 选中指标
        String rptDim = request.getParameter("rptDim");  // 选中维度
        String aliasRptName = request.getParameter("aliasRptName");  // 自定义文件名

        // 获取缓存的报表配置信息
        BaseRpt rptInfo = (BaseRpt) cacheManager.getRptCache(rptId);
        List<BaseRptColumn> conditionColumn = rptInfo.getConditionColumns();

        // 获取查询参数
        Map<String, String> paramMap = RequestParamToMap.convertToMap(request, conditionColumn);

        SelfDefine selfDefine = new SelfDefine();
        String userId = request.getParameter("userId");
        selfDefine.setUserId(userId);
        selfDefine.setRptName(aliasRptName);
        selfDefine.setItemCode(sysCode);
        selfDefine.setRptURL(rptURL);

        // 获取报表的查询条件
        List<Map<String, String>> paramList = new ArrayList<Map<String, String>>();
        if(paramMap != null && paramMap.size() > 0) {
            for(BaseRptColumn rptColumn : conditionColumn) {
                String isSQLColumn = rptColumn.getIsSQLColumn();
                if(Constants.YES.equals(isSQLColumn) || StringUtils.isBlank(isSQLColumn)) {
                    String aliasField = rptColumn.getAliasField();
                    String conditionType = rptColumn.getConditionType();  // 查询条件类型
                    String paramValue = paramMap.get(aliasField);  // 参数值

                    if (StringUtils.isNotBlank(paramValue) && !Constants.CONSTANTS_UNDEFINED.equalsIgnoreCase(paramValue)) {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put(aliasField, paramValue);
                        paramList.add(map);
                    } else {
                        // 查询条件是日期区间
                        if(Constants.CONDITIONTYPE_DATE_RANGE.equals(conditionType) || Constants.CONDITIONTYPE_VALUE_RANGE.equals(conditionType)) {
                            String dateStart = paramMap.get(aliasField + "_start");
                            String dateEnd = paramMap.get(aliasField + "_end");
                            if(StringUtils.isNotBlank(dateStart) || StringUtils.isNotBlank(dateEnd)) {
                                if(StringUtils.isNotBlank(dateStart)) {
                                    Map<String,String> map = new HashMap<String, String>();
                                    map.put(aliasField + "_start", dateStart);
                                    paramList.add(map);
                                }
                                if(StringUtils.isNotBlank(dateEnd)) {
                                    Map<String,String> map = new HashMap<String, String>();
                                    map.put(aliasField + "_end", dateEnd);
                                    paramList.add(map);
                                }
                            }
                        } else if(Constants.CONDITIONTYPE_TREE.equals(conditionType)) {
                            String treeDataName = paramMap.get(aliasField + "Id");
                            String treeDataId = paramMap.get("hid_" + aliasField);
                            if(StringUtils.isNotBlank(treeDataName)) {
                                treeDataName = treeDataName.replaceAll("\'", "");
                                treeDataName = treeDataName.replaceAll("\"", "");
                                Map<String, String> nameMap = new HashMap<String, String>();
                                nameMap.put(aliasField + "Id", treeDataName);

                                Map<String, String> idMap = new HashMap<String, String>();
                                idMap.put("hid_" + aliasField, treeDataId);

                                paramList.add(nameMap);
                                paramList.add(idMap);
                            }
                        }
                    }
                }
            }

            // 当查询条件不是来源于页面form表单，查询条件由上一个页面下钻而来
            List<BaseRptColumn> rptColumns = rptInfo.getRptColumns();
            List<BaseRptColumn> hiddenColumns = rptInfo.getHiddenRptColumns();
            String initParam = rptInfo.getInitCondition();
            String[] initParams = initParam.split(",");
            for(int i=0; i<initParams.length; i++) {
                boolean flag = true;
                String aliasField = initParams[i];
                String paramValue = paramMap.get(aliasField);  // 参数值
                String field = "";
                if(rptColumns != null && rptColumns.size() > 0) {
                    for(BaseRptColumn rptColumn : rptColumns) {
                        String columnField = rptColumn.getAliasField();
                        String isCondition = rptColumn.getIsCondition();
                        if(!Constants.YES.equals(isCondition)) {  // 查询条件列已经拼接，在此需要过滤，防止重复
                            if(aliasField.equals(columnField)) {
                                field = rptColumn.getAliasField();
                                flag = false;
                                break;
                            }
                        }
                    }
                }
                if(flag) {
                    if(hiddenColumns != null && hiddenColumns.size() > 0) {
                        for(BaseRptColumn rptColumn : hiddenColumns) {
                            String columnField = rptColumn.getAliasField();
                            String isCondition = rptColumn.getIsCondition();
                            if(!Constants.YES.equals(isCondition)) {
                                if(aliasField.equals(columnField)) {  // 查询条件列已经拼接，在此需要过滤，防止重复
                                    field = rptColumn.getAliasField();
                                    break;
                                }
                            }
                        }
                    }
                }

                if(StringUtils.isNotBlank(paramValue) && !Constants.CONSTANTS_UNDEFINED.equalsIgnoreCase(paramValue)) {
                    Map<String, String> map = new HashMap<String, String>();
                    paramValue = paramValue.replaceAll("\'", "");
                    paramValue = paramValue.replaceAll("\"", "");
                    map.put(field, paramValue);
                    paramList.add(map);
                }
            }
        }
        Map<String, String> idxMap = new HashMap<String, String>();
        Map<String, String> dimMap = new HashMap<String, String>();
        idxMap.put("rptIdx", rptIdx);
        dimMap.put("rptDim", rptDim);
        paramList.add(idxMap);
        paramList.add(dimMap);
        selfDefine.setConditions(paramList);

        return selfDefine;
    }

    /**
     * 调用第三方服务,实现自定义报表
     * @param url 外部服务地址
     * @param requestInfo 调用外部服务传递的参数
     * @return
     */
    @Override
    public HttpResult callThirdService(String url, IRequestInfo requestInfo) {
        HttpResult httpResult = new HttpResult();
        String json = JSONObject.toJSONString(requestInfo);
        try {
            httpResult = httpClientService.doPostJson(url, json);
            String body = httpResult.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            String status = jsonObject.getString("status");
            String msg = jsonObject.getString("msg");
            httpResult.setStateCode(Integer.valueOf(status));
            httpResult.setBody(msg);
            System.out.println("****调用PCS自定义报表服务[" + url + "]成功");
        } catch (Exception e) {
            System.out.println("***调用PCS自定义报表服务[" + url + "]失败");
            e.printStackTrace();
            httpResult.setStateCode(0);
            httpResult.setBody("自定义报表失败");
        }
        return httpResult;
    }
}
